<?php

use Illuminate\Support\Facades\Http;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\Session;
use Psy\Util\Str;

function removeSearchFromUrl(string $url): string
{
  if (false !== strpos($url, '/search')) {
    $url = str_replace("/search", "", $url);
  }
  return $url;
}

function addParamsToUrl(string $url, array $params): string
{
  $lsResult = $url;

  foreach ($params as $param => $value) {
    if (false === strpos($lsResult, '?')) {
      $lsResult .= '?';
    } else {
      $lsResult .= '&';
    }
    $lsResult .= $param . '=' . $value;
  }

  return $lsResult;
}

function addLocaleToUrl(string $url): string
{
  $params = $locale = null;

  $locale = Session::get('fullLocale');
  if ($locale != null) {
    $params['locale'] = $locale;
    $url = addParamsToUrl($url, $params);
  }

  return $url;
}

function addIncludeToUrl(string $url, array $params): string
{
  $lsResult = $url;

  foreach ($params as $param => $value) {
    if (false === strpos($lsResult, '?')) {
      $lsResult .= '?';
    } else {
      $lsResult .= '&';
    }
    $lsResult .= 'include[]' . '=' . $value;
  }

  return $lsResult;
}

function getFromCoreApi(string $bearer, string $url, string $key1 = null, string $key2 = null)
{
  $endpointResponse = $resultsData = $resultsKey1 = $resultsKey2 = null;

  $url = addLocaleToUrl($url);
  $endpointResponse = Http::withHeaders([
    'Authorization' => 'Bearer ' . $bearer
  ])->get($url);
  $resultsData = json_decode($endpointResponse, true);
  $resultsKey1 = $resultsData;
  if (isset($key1)) {
    $resultsKey1 = $resultsData[$key1];
    if (isset($key2)) {
      $resultsKey2 = $resultsKey1[$key2];
    }
  }

  return ($resultsKey2 ? $resultsKey2 : $resultsKey1);
}

function delFromCoreApi(string $bearer, string $url)
{
  $endpointResponse = null;

  $url = addLocaleToUrl($url);
  $endpointResponse = Http::withHeaders([
    'Authorization' => 'Bearer ' . $bearer
  ])->delete($url);

  return $endpointResponse;
}

function postToCoreApi(string $bearer, string $url, array $data)
{
  $endpointResponse = null;

  $url = addLocaleToUrl($url);
  $endpointResponse = Http::withHeaders([
    'Authorization' => 'Bearer ' . $bearer
  ])->post($url, $data);

  return $endpointResponse;
}

function putToCoreApi(string $bearer, string $url, array $data)
{
  $endpointResponse = null;

  $url = addLocaleToUrl($url);
  $endpointResponse = Http::withHeaders([
    'Authorization' => 'Bearer ' . $bearer
  ])->put($url, $data);

  return $endpointResponse;
}
